package com.dd.shop4j.console.goods.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.dd.shop4j.goods.mapper.GoodsCategMapper;
import com.dd.shop4j.goods.model.GoodsCateg;

/**
 * 商品分类管理<br />
 * <ul style="list-style: decimal;">
 *   <li>查询商品所有分类</li>
 *   <li>获取商品分类的树型结构数据</li>
 *   <li>递归创建tree结构数据</li>
 *   <li>添加商品分类信息</li>
 *   <li>根据商品分类id删除商品分类信息</li>
 *   <li>根据分类id获得分类信息</li>
 *   <li>修改商品分类信息</li>
 * </ul>
 * @author tangshu
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GoodsCategManagerService {

	@Resource private GoodsCategMapper goodsCategMapper;
	
	/**
	 * 查询商品所有分类
	 * @return
	 */
	public List<GoodsCateg> getAllGoodsCateg() {
		return goodsCategMapper.queryBySelective(null);
	}
	
	/**
	 * 获取商品分类的树型结构数据
	 * @return
	 */
	public String getGoodsCategTree() {
		List<GoodsCateg> categs = getAllGoodsCateg();
		JSONArray array = new JSONArray();
		for (GoodsCateg categ : categs) {
			if (categ.getParentId() == null || categ.getParentId() == 0) {
				JSONObject node = JSONObject.fromObject(categ);
				buildTree(node, categs);
				array.add(node);
			}
		}
		return array.toString();
	}
	
	/**
	 * 递归创建tree结构数据
	 * @param node
	 * @param categs
	 */
	private void buildTree(JSONObject node,
			List<GoodsCateg> categs) {
		JSONArray children = null;
		if (node.containsKey("children")) {
			children = node.getJSONArray("children");
		} else {
			children = new JSONArray();
		}
		for (GoodsCateg categ : categs) {
			if (categ.getParentId() != null
					&& node.getInt("id") == categ.getParentId().intValue()) {
				JSONObject childNode = JSONObject.fromObject(categ);
				buildTree(childNode, categs);
				children.add(childNode);
			}
		}
		node.put("children", children);
	}
	
	/**
	 * 添加商品分类信息
	 * @param categ
	 */
	public void insertGoodsCateg(GoodsCateg categ) {
		goodsCategMapper.insertSelective(categ);
	}
	
	/**
	 * 根据商品分类id删除商品分类信息
	 * @param categId 分类id
	 */
	public void deleteGoodsCateg(Integer categId) {
		goodsCategMapper.deleteByPrimaryKey(categId);
	}

	/**
	 * 根据分类id获得分类信息
	 * @param categId
	 * @return
	 */
	public GoodsCateg loadGoodsCateg(Integer categId) {
		return goodsCategMapper.selectByPrimaryKey(categId);
	}

	/**
	 * 修改商品分类信息
	 * @param categ
	 */
	public void updateGoodsCateg(GoodsCateg categ) {
		goodsCategMapper.updateByPrimaryKey(categ);
	}
	
}
